/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2020年9月28日
 */
package com.massyframework.beanskin.runtime.service.instrument;

import java.io.File;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.massyframework.beanskin.ModuleIdentifier;
import com.massyframework.beanskin.ModuleRuntimeException;
import com.massyframework.beanskin.SimpleModuleIdentifier;
import com.massyframework.beanskin.framework.FrameworkConfig;
import com.massyframework.beanskin.launching.LaunchingHandler;
import com.massyframework.beanskin.util.exceptioncollect.ExceptionCollectUtils;
import com.massyframework.beanskin.util.localstore.LocalStore;
import com.massyframework.beanskin.util.sorting.Order;
import com.massyframework.beanskin.util.sorting.Ordered;


/**
 * 增强启动器
 * @author huangkh
 *
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
public final class InstrumentationInitializer implements LaunchingHandler {

	private static final String AGENT_CLASSNAME = "com.massyframework.beanskin.launching.instrument.agent.InstrumentationAgent";
	private static final String METHOD_NAME = "getInstrumentation";
	
	private Logger logger = LoggerFactory.getLogger(InstrumentationInitializer.class);

	/**
	 * 
	 */
	public InstrumentationInitializer() {

	}

	@Override
	public void init(FrameworkConfig config) {
		LocalStore localStore = config.getBean(LocalStore.class.getName(), LocalStore.class);
		if (localStore != null) {
			ModuleIdentifier identifier =
					SimpleModuleIdentifier.createModuleIdentifierWithKernel();
			Path path = localStore.getDeploymentDirectory(identifier).resolve("agent".concat(File.separator).concat("beanskin-instrument-agent.jar"));
			if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
				URL url = this.getClass().getClassLoader().getResource("BEANSKIN-INF/agent/beanskin-instrument-agent.jar");
				if (url != null) {
					try {
						Files.createDirectories(path.getParent());
						Files.copy(url.openStream(), path, StandardCopyOption.REPLACE_EXISTING);
					} catch (IOException e) {
						if (logger.isErrorEnabled()) {
							logger.error(e.getMessage(), e);
						}
						throw new ModuleRuntimeException(identifier, e);
					}
				}
			}
			
			try {
				VirtualMachineHelper helper = new VirtualMachineHelper();			
				helper.attach(path.toFile().getPath());
				config.addListener(helper);
				
				Instrumentation inst = this.tryRetrieveInstrumentation();
				if (inst != null) {
					config.defineExportService(Instrumentation.class.getName(), inst, builder->{
						builder.addExportService(Instrumentation.class)
							.topRanking();
					});
				}
			}catch(Exception e) {
				if (logger.isErrorEnabled()) {
					logger.error(e.getMessage(), e);
				}
				ExceptionCollectUtils.addException(e);
			}
		}
	}
	
	/**
	 * 尝试获取{@link Instrumentation}接口
	 * 
	 * @return {@link Instrumentation}
	 * @throws ClassNotFoundException    类没找到时抛出的例外
	 * @throws SecurityException         方法不允许访问时抛出的例外
	 * @throws NoSuchMethodException     没有对应方法时抛出的例外
	 * @throws IllegalArgumentException  无效参数时抛出的例外
	 * @throws IllegalAccessException    无效访问时抛出的例外
	 * @throws InvocationTargetException 调用目标方法时发生的例外
	 */
	protected Instrumentation tryRetrieveInstrumentation()
			throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		ClassLoader loader = ClassLoader.getSystemClassLoader();
		Class<?> clazz = loader.loadClass(AGENT_CLASSNAME);
		if (clazz != null) {

			Method method = clazz.getMethod(METHOD_NAME, new Class<?>[0]);
			Instrumentation result = (Instrumentation) method.invoke(clazz, new Object[0]);
			if (result != null) {
				if (logger.isInfoEnabled()) {
					logger.info("retrieve Instruemtation success.");
				}
				return new InstrumentationWrapper(result);
			}
		}
		return null;
	}

	@Override
	public String toString() {
		return "InstrumentationInitHandler";
	}
		
}
